package operator

import (
	"gitee.com/bupt-zkjc/fabric2.2-interface/config_yaml"
	"gitee.com/bupt-zkjc/fabric2.2-interface/constant"
	"gitee.com/bupt-zkjc/fabric2.2-interface/entity"
	fautil "gitee.com/bupt-zkjc/fabric2.2-interface/util"
	"path/filepath"
	"strings"
)

type PeerOperator struct {
}

func (l *PeerOperator) AddNewPeer(peer entity.Peer) (string, error) {
	peerName := strings.Split(peer.PeerName, ",")
	peerUrl := strings.Split(peer.PeerLocation, ",")
	peers := ""
	urls := ""
	for i := range peerName{
		peers = peers + constant.Separator + peerName[i]
		urls = urls + constant.Separator + peerUrl[i]
	}
	/**
	使用脚本更新sdk配置文件，添加新节点的所有信息
	addPeers.sh 配置文件 节点名称 节点URL
	 */
	path, err := config_yaml.GetParentDirectory()
	command :=  constant.AddPeers + constant.Separator + "config_" + peer.ChainName + constant.Yaml + peers + urls
	err = fautil.Exec_shell(command, filepath.Join(path, constant.Dirpath))
	if err != nil{
		logger.Error(err)
		return "Update yaml file failure", err
	}

	logger.Info("SDK---Add new peer success!")
	return "Add new peer success", nil
}

func (l *PeerOperator) RemovePeer(peer entity.Peer) (string, error) {

	// 使用脚本更新sdk配置文件，添加新节点的所有信息 addPeers.sh 配置文件 节点名称 节点URL
	path, err := config_yaml.GetParentDirectory()
	command :=  constant.RemovePeer + constant.Separator + "config_" + peer.ChainName + constant.Yaml + peer.OrgName
	err = fautil.Exec_shell(command, filepath.Join(path, constant.Dirpath))
	if err != nil{
		logger.Error(err)
		return "Update yaml file failure", err
	}

	logger.Info("SDK---Add new peer success!")
	return "Add new peer success", nil
}
